package viv.karaoke.book;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class favouriteDataSource {
	
	// Database fields
	private SQLiteDatabase database;
	private mySQLiteHelper dbHelper;
	
	private String[] favouriteColumns = {
				 mySQLiteHelper.FAVOURITE_ID,
				 mySQLiteHelper.FAVOURITE_USER_ID,
				 mySQLiteHelper.FAVOURITE_SONG_ID
				 };

	public favouriteDataSource(Context context) {
	dbHelper = new mySQLiteHelper(context);
	}
	
	public void open() throws SQLException {
	database = dbHelper.getWritableDatabase();
	}
	
	public void close() {
	dbHelper.close();
	}
	
	public favourite createFavourite(long userId, long songId) {
		Cursor cursor = null;
		favourite newfavourite = new favourite();
		
		try{
			ContentValues values = new ContentValues();
		
			values.put(mySQLiteHelper.FAVOURITE_USER_ID, userId);
			values.put(mySQLiteHelper.FAVOURITE_SONG_ID, songId);		
			//values.put("userId", userId);
			//values.put("songId", songId);		
			    
			long insertId = database.insert(mySQLiteHelper.TABLE_FAVOURITE, null, values);
			//long insertId = database.insert("favourite", null, values);
			    
			cursor = database.query(mySQLiteHelper.TABLE_FAVOURITE, favouriteColumns, mySQLiteHelper.FAVOURITE_ID + " = " + insertId, null, null, null, null);
		
			cursor.moveToFirst();
			newfavourite = cursorToFavourite(cursor);
		}
		catch(Exception ex)
		{			
			ex.printStackTrace();
		}
		finally
		{
			//Make sure to close the cursor
			cursor.close();
		}
		
	    return newfavourite;
	}
	
	public void deleteFavourite(long id) {		    
		    System.out.println("Favourite deleted with id: " + id);
		    database.delete(mySQLiteHelper.TABLE_FAVOURITE, mySQLiteHelper.FAVOURITE_ID
		        + " = " + id, null);
	}

	private favourite cursorToFavourite(Cursor cursor) {
		favourite favourite = new favourite();
		
		favourite.setFavouriteId(cursor.getLong(0));
		favourite.setUserId(cursor.getLong(1));
		favourite.setSongId(cursor.getLong(2));
	    
	    return favourite;
	  }	
}